<template>
  <div :class="{ 'history-list-container': true, fold: !isShowHistory }">
    <div class="section-header">
      <span v-show="isShowHistory" class="count"
        >更改数（{{ historyList.length }}）</span
      >
      <a-icon-font
        class="icon"
        type="iconicon-beifen-right"
        @click="toggleDisplayMode"
      />
    </div>
    <div class="content">
      <template v-if="historyList.length > 0">
        <div
          v-for="item in historyList"
          :key="item.data.id"
          :class="{
            list: true,
            active: item.data.id === currentHistory.data.id,
            error: item.data.status !== 'SUCCESS',
          }"
          @click="setActive(item)"
        >
          <div class="icon">
            <a-icon-font
              v-if="item.data.status === 'SUCCESS'"
              :type="
                filterActionIconType[
                  item.data.actionType || item.data.action
                ] || 'iconqingxi-copy'
              "
            />
            <a-icon-font v-else type="iconwuquanxian" />
          </div>
          <div class="list-content">
            <!-- <div class="title">{{item.data.label === '原始数据' ? `${item.data.label}` : `${item.data.label}${filterActionTypeName[item.data.actionType] ? '-' : ''}${filterActionTypeName[item.data.actionType] || ''}`}}</div> -->
            <div class="title">{{ item.data.label }}</div>
            <div
              class="description"
              :title="
                item.data.label === '原始数据'
                  ? item.data.label
                  : `${item.data.col ? item.data.col + '：' : ''}${
                      item.data.description
                    }`
              "
            >
              {{
                item.data.label === '原始数据'
                  ? `${item.data.label}`
                  : `${item.data.col ? item.data.col + '：' : ''}${
                      item.data.description
                    }`
              }}
            </div>
            <div
              v-if="item.data.status !== 'SUCCESS'"
              class="error-message"
              :title="JSON.parse(item.data.logInfo).error_msg"
            >
              {{ JSON.parse(item.data.logInfo).error_msg }}
            </div>
            <div
              v-show="item.data.label !== '原始数据' && !isLock"
              class="btn-box"
            >
              <a-icon-font
                v-show="isShowEditButton(item)"
                class="btn"
                type="iconicon-beifen6"
                @click="onEditHistory($event, item)"
              />
              <a-icon-font
                v-show="!isVisitor"
                class="btn"
                type="iconicon-beifen1"
                @click="onDeleteHistory($event, item)"
              />
            </div>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="empty-info">
          无数据更改
        </div>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import DataStore, { IKeyValueStore } from '@/store/modules/dataview'
import { apiGetTableData } from '@/api/data-clean'
import { isEqual } from 'lodash'
import {
  DisableEditAction,
  filterActionIconType, // 清洗操作的图标
} from '@/util/data-selection-actions'

const disableEditAction = new Set(DisableEditAction) // 不可编辑的actionType

// export const filterActionTypeName = {
//   'filter-null': 'Null值筛选',
//   'filter-wildcard': '通配符匹配',
//   'filter-selected': '特定值',
//   'filter-number-range': '值范围',
//   'filter-date-range': '日期范围',
//   'filter-group': '分组',
//   'split-column': '拆分',
//   'merge-column': '合并字段',
//   'clean-from-vis': '可视化清洗'
// }

/**
 * 清洗action对应的图标
 */

@Component({})
export default class HistoryList extends Vue {
  @Prop() isShowHistory: boolean = false

  public get isLock() {
    return DataStore.getLock
  }

  private get filterActionIconType() {
    return filterActionIconType
  }

  public get selectNode() {
    return DataStore.selectNode
  }
  public get historyList() {
    return DataStore.historyList
  }

  public get errorHistoryList() {
    return this.historyList.filter((item) => item.data.status !== 'SUCCESS')
  }

  private get currentHistory() {
    return DataStore.currentHistory || { data: {} }
  }

  private get isVisitor() {
    return DataStore.isVisitor
  }

  private isShowEditButton(item: any) {
    let isShow = true
    if (
      disableEditAction.has(item.data.actionType) ||
      item.data.status !== 'SUCCESS' ||
      this.isVisitor
    ) {
      // 新增当清洗记录是-根据示例新增列的情况时
      isShow = false
    }
    if (item.data.actionType === 'aggreFunc' && item.data.resultType === '2') {
      //  聚合函数 - 生成新表 - 无法编辑操作历史
      isShow = false
    }
    return isShow
  }

  public get selectNodeTableInfo() {
    // 节点id和表名组成的唯一信息
    return DataStore.selectNodeTableInfo || { nodeId: '', tableName: '' }
  }

  /**
   * 当选择的节点变化时，重新触发获取数据
   */
  @Watch('selectNodeTableInfo', { immediate: true, deep: true })
  getCurrentGridItemId(newValue: any, oldValue: any): void {
    if (!newValue) {
      // DataStore.setTableData({
      //   head: [],
      //   data: [] // 清空
      // })
      DataStore.setLastHistoryCompleteId('')
      return
    }
    if (isEqual(newValue, oldValue) || newValue?.nodeId === oldValue?.nodeId) {
      // id变化才进行触发
      return
    }
    const { nodeId: newId } = newValue || {}
    const { nodeId: oldId } = oldValue || {}
    if (newId !== oldId) {
      DataStore.setLastHistoryCompleteId('')
    }
    if (newValue.nodeId && +this.selectNode.type === 5) {
      // 5为清洗节点
      // DataStore.setTableData({
      //   head: [],
      //   data: [] // 清空
      // })
      this.getHistoryList()
    } else {
      DataStore.setHistoryList({ historyList: [] })
    }
    DataStore.setIsEditHistory(false) // 清空历史操作编辑状态
    DataStore.clearTableSelection() // 清空清洗推荐的选中态
    DataStore.setTableVrCurrenSetMode(null)
  }

  toggleDisplayMode() {
    this.$emit('toggle-history-mode', false)
  }

  /**
   * 获取操作历史列表
   */
  getHistoryList() {
    DataStore.getHistoryList()
  }

  /**
   * 删除操作历史记录
   */
  async onDeleteHistory(event: Event, history: IKeyValueStore) {
    event.stopPropagation()
    DataStore.setVrEditTrigger(-1)
    DataStore.setShowColumnIndex(false)
    const response = await DataStore.delHistory({
      id: history.data.id,
    })
    if (!response.success) {
      this.$message.error(response.message)
      return
    }
    DataStore.refreshTaskQueryById(+this.selectNodeTableInfo.nodeId)
    DataStore.getHistoryList()
    DataStore.setConfirmEditTime(+new Date()) // 更新时间，触发后续节点的更新
    this.$message.success('操作成功')
  }

  /**
   * 设置推荐面板编辑标识
   */
  private checkEditTrigger(history: IKeyValueStore) {
    if (
      /^(column)|(selection)|(cell)|(row)(columnMergeColumns)|(formulaColumn)/.test(
        history.data.actionType
      )
    ) {
      const newValue = { ...history }
      const oldValue = { ...this.currentHistory }
      delete newValue.__stamp
      delete oldValue.__stamp
      const tag = isEqual(newValue, oldValue)

      DataStore.clearTableSelection() // 清空当前选中信息
      DataStore.setTableVrCurrenSetMode(null) // 清空表格模式选中
      // 需要同步数据
      if (!tag) {
        this.refreshTableData(history, () => {
          DataStore.setVrEditTrigger()
        })
      } else {
        DataStore.setCurrentHistory(history)
        DataStore.setVrEditTrigger()
      }
      return true
    }
    DataStore.setVrEditTrigger(-1)
    return false
  }

  /**
   * 编辑操作历史记录
   * 分两种情况：
   * 1、对当前处于选中态的历史点编辑按钮（不需要重新获取表、列信息，只需要切换成编辑态）
   * 2、切换到另一个历史记录并编辑（需要重新获取表、列信息，再切换成编辑态）
   */
  async onEditHistory(event: Event, history: IKeyValueStore) {
    event.stopPropagation()
    const triggerTag = this.checkEditTrigger(history) // 如果triggerTag 标记为true 则直接走了推荐面板的编辑
    if (!triggerTag) {
      if (
        this.currentHistory &&
        this.currentHistory.data.id !== history.data.id
      ) {
        // 针对2中的情况
        // DataStore.setTableData({ // 先清空，避免直接在旧数据上触发编辑态
        //   head: [],
        //   data: []
        // })
        DataStore.setSelectNodeTableInfo({
          // 表名改变，触发重新获取数据
          ...this.selectNodeTableInfo,
          tableName: history ? history.data.table : '',
        })
      }
      DataStore.setCurrentHistory(history)
      DataStore.setIsEditHistory(true)

      // DataStore.setIsEditHistory(true)
      // const newValue = {...history}
      // const oldValue = {...this.currentHistory}
      // delete newValue.__stamp
      // delete oldValue.__stamp
      // if (isEqual(newValue, oldValue)) { // 针对1的情况加上时间戳来触发historyChange的事件，便于DataColumns中watch到去触发编辑
      //   history = {
      //     ...history,
      //     __stamp: +(new Date())
      //   }
      //   DataStore.setCurrentHistory(history)
      // } else { // 针对2中的情况，先重新获取表、列信息，再改变currentHistory的数据
      //   await this.refreshTableData(history)
      // }
    } else {
      //  如果triggerTag 标记为true 直接走了推荐面板的编辑
      DataStore.toggleEnableVRPanelRecommend(true)
    }
  }

  /**
   * 设置操作历史选择态
   */
  setActive(history: IKeyValueStore) {
    DataStore.setShowColumnIndex(false)
    DataStore.setVRPanelShow(false)
    DataStore.setVrEditTrigger(-1)
    DataStore.setIsEditHistory(false) // 清空历史操作编辑状态
    DataStore.clearTableSelection()
    DataStore.setTableVrCurrenSetMode(null)
    if (history.data.status !== 'SUCCESS') {
      return
    }
    DataStore.setLastHistoryCompleteId('')
    if (
      this.currentHistory &&
      this.currentHistory.data.id !== history.data.id
    ) {
      // DataStore.setTableData({
      //   head: [],
      //   data: []
      // })
    }

    // DataStore.setTableData({
    //   head: [],
    //   data: []
    // })
    DataStore.setSelectNodeTableInfo({
      ...this.selectNodeTableInfo,
      tableName: history ? history.data.table : '',
    })
    DataStore.setCurrentHistory(history)
    // this.refreshTableData(history)
    this.$emit('change-history')
  }

  /**
   * 需要根据当前选中的历史重新请求数据
   * 包括刷新字段列信息、当前应处于的表名
   */
  async refreshTableData(history: IKeyValueStore, callback?: Function) {
    const response = await apiGetTableData({
      data: {
        curPage: 1,
        name: '_record_id_', // 如果没有字段，那就固定传 _record_id_
        pageSize: 50,
        filter: [],
        table: history && history.data.table, // 查询数据的表名取决于当前历史记录的表名
        taskId: this.selectNode.id,
      },
    })
    const result = response.data.result || {}

    DataStore.setTableData({
      head: result.head || [],
      data: result.data || [],
    })
    DataStore.setTableDataCount(result.page ? result.page.totalElements : 0)
    DataStore.setCurrentHistory(history)
    if (callback) {
      callback()
    }
  }
}
</script>

<style lang="less" scoped>
.history-list-container {
  background-color: #fff;
  border-top: 1px solid rgba(233, 233, 233, 0.8);
  height: 100%;
  width: 280px;

  .section-header {
    align-items: center;
    color: #373b52;
    display: flex;
    font-size: 14px;
    height: 38px;
    justify-content: space-between;
    padding: 0 10px 0 20px;
    width: 100%;

    .count {
      letter-spacing: 1.12px;
    }

    .icon {
      cursor: pointer;
      padding: 8px;
      transform: rotate(180deg);
    }
  }

  .content {
    background-color: #fff;
    height: calc(100% - 38px);
    overflow-y: auto;

    .list {
      display: flex;
      padding: 8px 10px 8px 16px;

      &.active {
        background-color: #eff0fe;
      }

      &.error {
        .list-content,
        .list-content .title {
          color: #f26740;
        }
      }

      .icon {
        margin-right: 10px;
        position: relative;
      }

      .icon::after {
        background-color: #d8d8d8;
        bottom: -1px;
        content: '';
        display: block;
        height: 16px;
        left: 6px;
        position: absolute;
        width: 1px;
      }

      .list-content {
        color: rgba(34, 36, 50, 0.6);
        flex: 1;
        font-size: 12px;
        letter-spacing: 1.12px;
        overflow: hidden;
        position: relative;
        text-overflow: ellipsis;
        white-space: nowrap;

        .title {
          color: #373b52;
          font-size: 14px;
          width: 180px;
        }

        .title,
        .description {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .btn-box {
          color: #5d637e;
          cursor: pointer;
          display: none;
          font-size: 16px;
          position: absolute;
          right: 0;
          top: 0;

          .btn {
            margin-right: 8px;
          }
        }

        &:hover .btn-box {
          display: block;
        }
      }
    }
  }

  .empty-info {
    color: rgba(34, 36, 50, 0.6);
    padding-top: 32px;
    text-align: center;
  }

  &.fold {
    width: 44px;

    .section-header {
      border-bottom: 0;
      height: auto;
      letter-spacing: 8px;
      padding: 10px 0;
      writing-mode: vertical-lr;
    }

    .icon {
      transform: rotate(0);
    }
  }
}
</style>
